/* eslint-disable */
import qs from 'qs'
import { Toast } from 'element-ui';

const files = require.context('~/api', false, /^\.\/(?!-).*\.(js)$/)
const filenames = files.keys()
function getModule (filename) {
  const file = files(filename)
  return file.default ? file.default : file
}
const api = {}
var loadingToast // 加载中
filenames.forEach(filename => {
  const name = filename.replace(/^\.\//, '').replace(/\.(js)$/, '')
  if (name === 'app') return false
  api[name] = getModule(filename)
})
export default  ({ app,$axios, redirect,store },inject) => {
    
  $axios.onRequest(config => {
    
    // console.log(config)
    if(config.loading){
      loadingToast = Toast.loading({
          duration: 0,       // 持续展示 toast
          forbidClick: true, // 禁用背景点击
        });
    }
    var postParams = qs.parse(config.data)
    var postJSON = postParams.data
    var postType = Object.prototype.toString.call(config.data)//判断是否是formData [object FormData] [object Object]
    if (postType =='[object FormData]') postParams=config.data //如果是文件
    var getParams = qs.parse(config.params)
    
    if (postJSON) {
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
    }
    if (postType =='[object FormData]') {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    //post获取传值才有config.data，get获取传值config.params
    const sequence=sessionStorage.getItem('sequence') ||''
    if(sequence) { //如果存在sequence,则提交流程一直携带
      if(config.method==='get') {
        config.params={
          ...config.params, 
          sequence:sequence
        }
      } else {
        if(postType =='[object FormData]') {
          config.data.append('sequence',sequence)
        }else {
          config.data={
            ...config.data, 
            sequence:sequence
          }
        }
      }
    }
    const accessToken=store.getters.accessToken || localStorage.getItem('accessToken')||'' // 获取access-token
    config.headers['Access-Token'] = accessToken // 设置access-token
    config.timeout=5000;
    if (postType !=='[object FormData]') {
      config.transformRequest = [
        data => {
          // data = postJSON ? JSON.stringify(config.method === 'delete' ? data : data.data) : qs.stringify(data) //不可删除（同上）
          data = postJSON ? JSON.stringify(data) : qs.stringify(data)
          return data
        }
      ]
    }
  })
  $axios.onResponse(response => {
    if(loadingToast) {
      loadingToast.clear()
    }
    const refreshToken=store.getters.refreshToken || localStorage.getItem('refreshToken')// 获取refresh-token
    const uid=store.getters.uid || localStorage.getItem('uid')// 获取uid
    try { //保存sequence,投保完成后取消
      if(response.data.data.sequence){
        sessionStorage.setItem('sequence',response.data.data.sequence)
      }
    } catch (error) {}
    
    const { data,config} = response
    if(config.url!=='http://api.insurance.freeradio.cn/agents/3/accessTokens'){
      
    }
    const { code, message } = data
    if (code !== '200') {
      switch (code) {
        case '407'://重新获取token,访问地址
          $axios.$post(`/agents/${uid}/accessTokens`,{ refreshToken: refreshToken}
          ).then((res) => {
            if (res.code==="200") {
              var data=res.data.agentTokenInfo
              store.dispatch('setAccessToken',data.accessToken)
              store.dispatch('setRefreshoken',data.refreshToken)
              var {method,url}=config
              var resData=method==='post' ?config.data : ''
              let dataObj = {}
              resData.split('&').map(v=>{
                var dataArr=v.split('=')
                dataObj[dataArr[0]]=dataArr[1]
              })
              var requestConfig={
                method:method,
                data:dataObj,
                url:url
              }
              return $axios(requestConfig)
            }
            if (res.code==="407") {
              Toast('会话已过期，请重新登陆');
              store.dispatch('unsetAgent')
              setTimeout(()=>{
                redirect({ path: '/users/login' })
              },1000)
            }
          })
          // })
          break
        case '401'://注销本地凭证重新登陆
          Toast('会话已过期，请重新登陆');
          store.dispatch('unsetAgent')
          setTimeout(()=>{
            redirect({ path: '/users/login' })
          },1000)
          break;
        default:
          Toast(message || '服务繁忙');
          break;
      }
    }
  })
  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (error.response) {
      const { data } = error.response
      Toast.fail(data.message);
    } else {
      Toast.fail('系统错误，请稍后重试~');
    }
    if (code === 400) {
      // redirect('/400')
      redirect({ name: 'element' })
    }
  })
  for (const key in api) {
    inject(key, api[key]($axios))
  }
}
